import React, { FC, useEffect } from 'react';
import * as d3 from 'd3';
import { options } from './config';

let _this: { [name: string]: any } = {
  circle_r: 30,
};
const D3_Demo: FC = () => {
  useEffect(() => {
    init();
  }, []);
  const onDrag = (dom: any, d: DragEvent, i: any) => {
    d3.select(dom).attr('transform', 'translate(' + d.x + ',' + d.y + ')');
    i.x = d.x;
    i.y = d.y;
    drawLink();
  };
  const init = () => {
    _this.svg = d3
      .select('#body')
      .append('svg')
      .attr('width', 500)
      .attr('height', 500)
      .attr('style', 'border:1px solid red');

    _this.container = _this.svg
      .append('g')
      .attr('transform', 'scale(' + 1 + ')');

    // 初始化节点
    _this.node = _this.container
      .selectAll('.node')
      .data(options.data)
      .enter()
      .append('g')
      .attr('transform', (d: { x: any; y: any }) => `translate(${d.x},${d.y})`)
      .attr('class', 'node')
      .call(
        d3
          .drag()
          .on('drag', function (d, i) {
            const dom: any = this;
            onDrag(dom, d, i);
          })
          .on('end', (d, i: any) => {})
      );

    _this.node.append('circle').attr('r', _this.circle_r).attr('fill', 'red');
    drawLink();
  };

  const drawLink = () => {
    /*
      M 0 100  //（0，100）是起点
        L 100 100  // 画一条直接到 (100,100)
        A 100 100 0 1 1 300 100  // 画一段圆弧
        L 400 100 //画一条直线到 (400,100)
      */
    if (_this.lineGroup && d3.selectAll('.link').nodes().length) {
      console.log(d3, d3.selectAll('.link').nodes());

      d3.selectAll('.link').attr('d', (link: any) => {
        // eslint-disable-next-line array-callback-return
        const obj = _this.node.filter((o: any) => {
          return o.id === link.source || o.id === link.target;
        });

        return `M ${obj.data()[0].x} ${obj.data()[0].y} L ${obj.data()[1].x} ${
          obj.data()[1].y
        }`;
      });
    } else {
      _this.lineGroup = _this.container.append('g');
      _this.lineGroup
        .selectAll('.link')
        .data(options.edges)
        .enter()
        .append('path')
        .attr('class', (link: any) => {
          return `link link-${link.source}-${link.target}`;
        })
        .attr('d', (link: any) => {
          // eslint-disable-next-line array-callback-return
          const obj = _this.node.filter((o: any) => {
            return o.id === link.source || o.id === link.target;
          });

          return `M ${obj.data()[0].x} ${obj.data()[0].y} L ${
            obj.data()[1].x
          } ${obj.data()[1].y}`;
        })
        .attr('stroke-width', '1px')
        .attr('stroke', 'blue');
    }
  };

  return <div id="body"></div>;
};

export default D3_Demo;
